﻿var ns, toast, actionsheet, WXPhotoPicker,fileBrowser,imageBrowser,docReader;
var app = new Vue({
    el: '#app',
    data: {
        ID:0,
        form: {
            ID: 0,
            Title: '',//通知标题
            UserIDs: '',//通知对象
            IsSendTime: false,//定时发送
            SendTime: '',//定时发布时间
            Content: '',//通知内容
        },
        showCalender: false,
        minDate: new Date(),
        maxDate: new Date(2050, 0, 1),
        currentDate:new Date(),
        wenjianlist:[],//选择的附件
        imgindex: 0,
        img_count: 0,
        select_imglist: [],
        select_imgindex: 0,
        maxuploadcount: CONFIG.maxuploadcount,
        fileID:0,
        // file:{
        //     ID:0,
        //     CredentialName:'',
        //     CredentialUrl:'',
        //     TypeName:'',//文件类型
        // },
        chhooseUserList:[],
        showup:false,
    },
    methods: {
        get_data: function () {
            var that = this;
            var options = {};
            options.ID = that.ID;
            options.Type = 2;
            options.action = "editinternaladd";
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.form.Title=data.newModel.NoticeTitle.trim();
                    that.form.IsSendTime=data.newModel.IsTiming;
                    that.form.SendTime='';
                    if(that.form.IsSendTime){
                        var newDate=ns.DealTimeYYMMDDHHSS(data.newModel.ReleaseTime);
                        that.currentDate=newDate;
                        that.form.SendTime=newDate;
                    }
                    setContentEditorContent(data.newModel.HTMLContent);
                    that.chhooseUserList=data.items;
                    that.wenjianlist=data.list;
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
        //选择通知对象
        open_more:function(){
            var that=this;
            ns.openWin('examine_Allperson', '全部通知对象', {
                list: that.chhooseUserList,
                type:0,
             }); 
        },
        //移除抄送人
        guanbi_pic:function(id){
            var that=this;
            that.chhooseUserList = that.chhooseUserList.filter((item) => {
                return item.UserID != id
            });   
        },
        do_choose_users: function () {
            var that = this;
            ns.openWin('chooseuser_frm', '选择通知对象');
        },
        do_choose_time: function () {
            var that = this;
            that.showCalender = true;
            if(that.ID<=0){
                that.minDate=new Date();
            }
        },
        doSelectRoom: function () {
            var that = this;
            that.form.IsSendTime=!that.form.IsSendTime;
            if (!that.form.IsSendTime) {
                that.form.SendTime = '';
            }
        },
        onConfirm(day) {
            var that = this;
            var y = day.getFullYear();
            var m = day.getMonth() + 1;
            var d = day.getDate();
            var h = day.getHours();
            var s = day.getMinutes();
            var nowdate = y + '-' + (m >= 10 ? m : '0' + m) + '-' + (d >= 10 ? d : '0' + d) + ' ' + (h >= 10 ? h : '0' + h) + ':' + (s >= 10 ? s : '0' + s);
            that.showCalender = false;
            that.form.SendTime = nowdate;
        },


         //上传附件
         do_openUp:function(){
            var that=this;
            that.showup=true;
        },
        //上传图片
        add_picture: function () {
            var that = this;
            that.showup=false;
            ns.confirmPer('camera', function () {
                that.choose_picture_start();
            })
        },
        choose_picture_start:function(){
            var that = this;
            if (that.wenjianlist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.actionSheet({
                cancelTitle: '取消',
                buttons: ['拍照', '从相册选择']
            }, function(ret, err) {
                //拍照
                if(ret.buttonIndex==1){ 
                    that.upload_choose_picture();
                    return;
                }
                //从相册选择
                if(ret.buttonIndex==2){
                    that.choose_picture_album();
                    return;
                } 
                //取消 
                else{
                    return false;  
                }  
            });
        },
        upload_choose_picture:function(){
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                destinationType: 'url',
                allowEdit: false,
                saveToPhotoAlbum: true,
            }, function(ret, err) {
                if (ret&&ret.data) {
                    var list = [];
                    list.push({
                        url: ret.data,
                    });
                    const params = {
                        action: "uploadfileone",
                    }
                    ns.post(params, function (succeed, data, err) {
                        if (succeed) {
                            // that.file.ID = data.file.ID;
                            // that.file.CredentialName = data.file.FileName;
                            // that.file.CredentialUrl = data.file.FullPath;
                            that.wenjianlist.push(data.file);
                            // that.file.TypeName= data.file.ContentType;
                            // console.log(JSON.stringify(that.wenjianlist));
                        }
                    }, {
                        files: {
                            file: list[0].url
                        }
                    })
                } 
            });
        },
        choose_picture_album:function(){
            var that = this;
            WXPhotoPicker.open({
                max: that.maxuploadcount - that.wenjianlist.length,
                type:'image',
            }, function(ret) {
                if (ret) {
                    if (ret.list.length > 0) {
                        ret.list.forEach((item) => {
                            var list = [];
                            list.push({
                                url: item.path,
                            });
                            const params = {
                                action: "uploadfileone",
                            }
                            ns.post(params, function (succeed, data, err) {
                                if (succeed) {
                                    that.wenjianlist.push(data.file);
                                }
                            }, {
                                files: {
                                    file: list[0].url
                                }
                            })
                        });
                    }
                }
            });
        },
        //上传文件
        add_wenjian: function () {
            var that = this;
            that.showup=false;
            fileBrowser.open({
                confirm: true
            }, function (ret) {
                fileBrowser.close();
                if (ret) {
                    const url = ret.url || ""
                    const params = {
                        action: "fileupload",
                    }
                    ns.post(params, function (succeed, data, err) {
                        if (succeed) {
                            // that.file.ID = data.imgs[0].ID;
                            // that.file.CredentialName = data.imgs[0].FileName;
                            // that.file.CredentialUrl = data.imgs[0].FilePath;
                            that.wenjianlist.push(data.imgs[0]);
                            // var i = that.file.CredentialName.lastIndexOf('.');
                            // var j = that.file.CredentialName.length;
                            // that.file.TypeName= that.file.CredentialName.slice(i + 1, j);
                        }
                    }, {
                        files: {
                            file: [url]
                        }
                    })
                    return;
                }
                return false;
            });
        },
        open_flie: function (item,index) {
            var that = this;
            var i = item.FileName.lastIndexOf('.');
            var j = item.FileName.length;
            var nameType= item.FileName.slice(i + 1, j);
            if(nameType=='png'||nameType=='jpg'||nameType == 'jpeg'||nameType=='tif'||nameType=='gif'){
                that.img_browser(item.FilePath);
            }else{
                that.do_openFile(item);
            }
            
        },
        img_browser: function(imgurl) {
            var that = this;
            var imgurls = [];
            imgurls.push(imgurl);
            imageBrowser.openImages({
                imageUrls: imgurls,
                showList: false,
                activeIndex: 0
            });
        },
        do_openFile:function(item){
            api.download({
                url: item.FilePath,
                savePath: 'fs://app/' + item.FileName,
                report: true,
                cache: true,
                allowResume: true
            }, function (ret, err) {
                if (ret.state == 1) {
                    docReader.open({
                        path: ret.savePath,
                        autorotation: false
                    }, function(ret, err) {
                        if (ret.status) {
                            // alert(JSON.stringify(ret));
                        } else {
                            alert(JSON.stringify(err));
                        }
                    });
                }else{
                    api.toast({
                        msg: '打开失败',
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            })
        },
        //删除文件
        do_delete: function (id) {
            var that=this;
            that.wenjianlist = that.wenjianlist.filter((item) => {
                return item.ID != id
            });
        },

        do_save: function () {
            var that = this;
            if (!that.form.Title) {
                api.toast({
                    msg: '请填写标题',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.chhooseUserList.length<=0) {
                api.toast({
                    msg: '请选择通知对象',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.form.IsSendTime&&that.form.SendTime=='') {
                api.toast({
                    msg: '请选择发布时间',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }


            const content = contentEditor.getContent();//获取富文本内容
            // console.log(JSON.stringify(content));

            var fileIDs = [];
            for (let item of  that.wenjianlist) {
                if (item.ModifyType != 1) {
                    fileIDs.push(item.ID);
                }   
            }

            var chooseUserIDs=[];
             for (let item of that.chhooseUserList) {
                chooseUserIDs.push(item.UserID);
            }

            var options = {};
            options.action = "savainternalnotification";
            options.ID = that.ID;
            options.tdTitle = that.form.Title;
            options.tdIsActive = that.form.IsSendTime;
            options.tdStartTime = that.form.SendTime;
            options.HTMLContent = content;
            options.hdUserIDs = JSON.stringify(chooseUserIDs);
            options.fileList=JSON.stringify(fileIDs);

            toast.loading({
                title: "提交中",
                duration: 2000
            }, function (ret) { });
            ns.post(options, function (succeed, data, err) {
                toast.hide();
                if (succeed) {
                    if(data.status){
                        api.toast({
                            msg: '提交成功',
                            duration: 2000,
                            location: 'bottom'
                        });
    
                        //刷新并关闭
                        setTimeout(() => {
                            api.sendEvent({
                                name: 'reloadneibulist',
                            });
                            api.sendEvent({
                                name: 'do_reload_neibu',
                            });
                            api.closeWin();
                        }, 300);
                    }
                    else{
                        api.toast({
                            msg: data.Msg,
                            duration: 2000,
                            location: 'bottom'
                        });  
                    }

                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
    }
});

var     contentEditor = new Eleditor({
    // 编辑区域dom对象
    el: '#contentEditor',
    // 图片上传自定义方法
    uploader: function () {
        return new Promise(function (_resolve, _reject) {
            openPhoto('pic', function (ret) {
                contentEditor.saveState();
                contentEditor.getEditNode().after(`
                            <img src="${ret}" />
                    `);
                contentEditor.hideEditorControllerLayer();
            }, function (err) {
                alert(err)
            });
        })
    },
    /*初始化完成钩子*/
    mounted: function () {

    },
    /*文档内容变化*/
    changer: function () {
    },
    /*自定义按钮的例子*/
    toolbars: [
        'insertText',
        'editText',
        'insertImage',
        'insertLink',
        'insertHr',
        'delete',
        //自定义一个视频按钮
        {
            id: 'insertVideo',
            name: '插入视频',
            handle: function (select, controll) {//回调返回选择的dom对象和控制按钮对象
                openPhoto('video', function (ret) {
                    contentEditor.saveState();
                    contentEditor.getEditNode().after(`
                            <div class='Eleditor-video-area'>
                                <video src="${ret}" autoplay="autoplay" controls="controls"></video>
                            </div>
                        `);
                    contentEditor.hideEditorControllerLayer();
                }, function (err) {
                    alert(err)
                });
                return false;
            }
        },
        'undo',
        'cancel'
    ],
    placeHolder: '图文信息插入'
});


apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    toast = new auiToast();
    actionsheet = new auiActionsheet();
    WXPhotoPicker = api.require('WXPhotoPicker');
    imageBrowser = api.require('imageBrowser');
    docReader = api.require('docReader');
    
    //上传附件组件
    fileBrowser = api.require('fileBrowser');
    app.ID = api.pageParam.id || 0;
    if(app.ID>0){
        app.get_data();
    }
    
    api.addEventListener({
        name: 'purchase_add'
    }, function (ret) {
        // console.log(JSON.stringify(ret.value.data));
        // app.chhooseUserList=ret.value.data;
        var chooseposList=app.chhooseUserList;
        chooseposList=chooseposList.concat(ret.value.data);
        var new_list=chooseposList.filter(function(element,index,self){
            return self.findIndex(el=>el.UserID==element.UserID)===index  //如果是根据name去重就江id改为name
          })
        // const new_list = [...new Set(chooseposList)];// 去重
        app.chhooseUserList = new_list;
       
    });

    api.addEventListener({
        name: 'purchase_update'
    }, function (ret) {
        app.chhooseUserList=ret.value.data;
    })
  
};


// 给编辑器写入文件
function setContentEditorContent(e) {
    setTimeout(() => {
        contentEditor.append(e);
    }, 1000)
}

function openPhoto(type, _resolve, _reject) {
    var title='选择图片';
    if(type=='video'){
        title='选择视频';
    }
    api.actionSheet({
        title:title,
        cancelTitle: '关闭',
        buttons: ['打开相机', '本地图库'],
        style: {
            fontNormalColor: '#777777',
            fontPressColor: '#e03b6c'
        }
    }, function (ret, err) {
        if(ret.buttonIndex==3){
            return;
        }
        api.getPicture({
            sourceType: ret.buttonIndex == 1 ? 'camera' : 'library',
            encodingType: "jpg",
            mediaValue: type, // pic video
            quality: 100,
            destinationType: 'url', //url  base64
            targetWidth: 768,
            targetHeight: 768,
            saveToPhotoAlbum: false,
            allowEdit: false
        }, function (ret, err) {
            if (ret && ret.data) {
                var options = {};
                options.action = "fileupload";
                var filelist = [];
                filelist.push(ret.data);
                ns.post(options, function(succeed, data, err) {
                    if (succeed) {
                        if(data.imgs.length<=0||data.imgs==undefined){
                            _reject('上传服务器失败!');
                            return;
                        }
                        let retimg=data.imgs[0];
                        _resolve(retimg.FilePath);
                    } else if (err) {
                        _reject(err);
                    }
                }, {
                    toast: true,
                    files: {
                        file: filelist
                    }
                });  
            } else {
                _reject('上传失败!');
            }
        });
    })

}

